<?php


namespace App\Http\Controllers\Api;

use App\Businesses\BusinessState;
use App\Services\Base\Interfaces\ConfigServiceInterface;
use App\Services\Base\Services\ConfigService;
use App\Services\Business\Interfaces\CourseServiceInterface;
use App\Services\Business\Interfaces\GroupServiceInterface;
use App\Services\Business\Interfaces\VideoServiceInterface;
use App\Services\Business\Models\Appraise;
use App\Services\Business\Models\Article;
use App\Services\Business\Models\Doubt;
use App\Services\Business\Services\BusinessService;
use App\Services\Business\Services\GroupService;
use App\Services\Business\Services\VideoService;
use App\Services\Member\Interfaces\RoleServiceInterface;
use App\Services\Member\Interfaces\SocialiteServiceInterface;
use App\Services\Member\Interfaces\UserServiceInterface;
use App\Services\Member\Services\DeliverService;
use App\Services\Member\Services\RoleService;
use App\Services\Member\Services\SocialiteService;
use App\Services\Member\Services\UserService;
use App\Services\Order\Interfaces\OrderServiceInterface;
use App\Services\Order\Services\OrderService;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Services\Member\Models\User;
use App\Services\Order\Models\Order;
use App\Services\Business\Models\Video;
use App\Services\Business\Models\Course;
use App\Services\Member\Models\UserRemark;
use App\Services\Member\Models\UserProfile;
use App\Services\Business\Models\CourseUserRecord;
use App\Services\Member\Models\UserCreditRecord;
use App\Services\Member\Notifications\SimpleMessageNotification;
use  App\Services\Member\Interfaces\DeliverServiceInterface;




class MemberController extends BaseController
{
    /**
     * @var UserService
     */
    protected $userService;
    /**
     * @var CourseService
     */
    protected $courseService;
    /**
     * @var VideoService
     */
    protected $videoService;
    /**
     * @var GroupService
     */
    protected $groupService;
    /**
     * @var RoleService
     */
    protected $roleService;
    /**
     * @var OrderService
     */
    protected $orderService;
    /**
     * @var SocialiteService
     */
    protected $socialiteService;

    protected $businessState;
    /**
     * @var ConfigService
     */
    protected $configService;
    /**
     * @var DeliverService
     */
    protected $deliverService;




    public function __construct(
        UserServiceInterface      $userService,
        CourseServiceInterface    $courseService,
        VideoServiceInterface     $videoService,
        GroupServiceInterface     $groupService,
        RoleServiceInterface      $roleService,
        OrderServiceInterface     $orderService,
        SocialiteServiceInterface $socialiteService,
        BusinessState             $businessState,
        DeliverServiceInterface   $deliverService,

        ConfigServiceInterface    $configService
    )
    {
        $this->userService = $userService;
        $this->courseService = $courseService;
        $this->videoService = $videoService;
        $this->roleService = $roleService;
        $this->groupService = $groupService;
        $this->orderService = $orderService;
        $this->socialiteService = $socialiteService;
        $this->businessState = $businessState;
        $this->configService = $configService;

        $this->deliverService = $deliverService;
    }





    public function detail($id)
    {
        $user = User::query()
            ->with([
                'role:id,name',
                'invitor:id,nick_name,mobile,avatar',
                'profile', 'tags:id,name',
                'remark:user_id,remark',
            ])
            ->where('id', $id)
            ->firstOrFail();

        return $this->successData([
            'data' => $user,
        ]);
    }


    public function userHistory(Request $request, $id)
    {
        $data = CourseUserRecord::query()->where('user_id', $id)->orderByDesc('created_at')->paginate($request->input('size', 20));
        $courseIds = get_array_ids($data->items(), 'course_id');
        $courses = Course::query()->whereIn('id', $courseIds)->select(['id', 'title', 'thumb', 'charge'])->get()->keyBy('id');
        return $this->successData([
            'data' => $data,
            'courses' => $courses,
        ]);
    }

    public function userOrders(Request $request, $id)
    {
        $data = Order::query()
            ->with(['goods', 'paidRecords'])
            ->where('user_id', $id)
            ->orderByDesc('created_at')
            ->paginate($request->input('size', 20));

        return $this->successData([
            'data' => $data,
        ]);
    }



    // 积分记录
    public function credit1Records(Request $request, $id)
    {
        $records = UserCreditRecord::query()
            ->where('user_id', $id)
            ->where('field', 'credit1')
            ->orderByDesc('id')
            ->paginate($request->input('size', 20));
        return $this->successData([
            'data' => $records,
        ]);
    }

    // 积分变动
    public function credit1Change(Request $request)
    {
        $userId = $request->input('user_id');
        $credit1 = $request->input('credit1');
        $remark = $request->input('remark', '');
        DB::transaction(function () use ($userId, $credit1, $remark) {
            $user = User::query()->where('id', $userId)->firstOrFail();

            $user->credit1 += $credit1;
            $user->save();

            UserCreditRecord::create([
                'user_id' => $userId,
                'field' => 'credit1',
                'sum' => $credit1,
                'remark' => $remark,
            ]);
        });

        return $this->success();
    }



    // 用户备注

    /**
     * @param $id
     * @return JsonResponse
     */
    public function remark($id)
    {
        $userRemark = UserRemark::query()->where('user_id', $id)->first();
        $remark = $userRemark ? $userRemark['remark'] : '';
        return $this->successData([
            'remark' => $remark,
        ]);
    }




    // 更新用户备注


    public function sendMessageMulti(Request $request)
    {
        $message = $request->input('message');
        $userIds = $request->input('user_ids');

        if (!is_array($userIds) || !$userIds) {
            return $this->error('请选择需要发送消息的用户');
        }
        if (!$message) {
            return $this->error('请输入需要发送的消息');
        }
        if (count($userIds) > 100) {
            return $this->error('单次发送消息不能超过100人');
        }

        $users = User::query()->whereIn('id', $userIds)->get();
        foreach ($users as $user) {
            $user->notify(new SimpleMessageNotification($message));
        }

        return $this->success();
    }

    public function sendMessage(Request $request, $userId)
    {
        $user = User::query()->where('id', $userId)->firstOrFail();
        $message = $request->input('message');
        if (!$message) {
            return $this->error(__('参数错误'));
        }

        $user->notify(new SimpleMessageNotification($message));

        return $this->success();
    }

    public function userVideoWatchRecords(Request $request, $id)
    {
        $records = UserVideoWatchRecord::query()
            ->select([
                'id', 'user_id', 'course_id', 'video_id', 'watch_seconds', 'watched_at', 'created_at',
            ])
            ->where('user_id', $id)
            ->orderByDesc('id')
            ->paginate($request->input('size', 10));

        $videos = [];
        $videoIds = array_column($records->items(), 'video_id');
        if ($videoIds) {
            $videos = Video::query()->whereIn('id', $videoIds)->select(['id', 'title'])->get()->keyBy('id');
        }

        return $this->successData([
            'data' => $records,
            'videos' => $videos,
        ]);
    }



    public function subscribes(Request $request, string $type, int $id)
    {


        $size = $request->input('size', 10);
        $keywords = $request->input('keywords', '');
        $is_expired = $request->input('is_expired', 0);
        $model = 'App\Services\Member\Models\User' . ucfirst($type);
        $model = new $model();

        $userIds = [];
        if ($keywords) {
            $userIds = User::query()
                ->when($keywords, function ($query) use ($keywords) {
                    $query->where('nick_name', 'like', '%' . $keywords . '%')
                        ->orWhere('mobile', $keywords)
                        ->orWhere('id', $keywords);
                })
                ->select(['id'])->get()->pluck('id')->toArray();
        }
        // 课程订阅数量更新
        $members = $model::query()
            ->with(['member'])
            ->select(['*', DB::raw('DATEDIFF(expired_at, NOW()) AS expired_days')])
            ->when($is_expired, function ($query) use ($is_expired) {
                return $query->where('expired_time', '<', Carbon::now());
            })
            ->when($keywords, function ($query) use ($userIds) {
                $query->whereIn('user_id', $userIds);
            })
            ->where($type . '_id', $id)
            ->orderBy('created_at')
            ->paginate($size);
        return $this->successData(compact('members'));

    }







}
